﻿using System;
using System.Collections.Generic;
using System.IO;
using MSW = Microsoft.Office.Interop.Word;
using EXC = Microsoft.Office.Interop.Excel;

namespace SubCom_Doc2Pdf
{
    internal class Xls2PdfViaOffice : Convertor
    {
        public Xls2PdfViaOffice(Target target) : base(target)
        {
            List<string> list = new List<string>();
            list.Add("EXCEL");
            SetTargetApps(list);   
        }

        protected override void OnProcess(Target target)
        {
            string src = target.Sources;
            string dest = target.Destination;

            EXC.Application MSExcel = new EXC.Application();
            MSExcel.DisplayAlerts = false;
            MSExcel.Visible = false;
            EXC.Workbook wb = null;
            try
            {
                wb = MSExcel.Workbooks.Open(@src, ReadOnly: true);
                wb.Activate();
                EXC.Worksheet ws = (EXC.Worksheet)MSExcel.ActiveSheet;
                String cellVal = ws.Cells[1, 1].Value + " ";
                ws.Cells[1, 1] = cellVal;
                wb.ExportAsFixedFormat(EXC.XlFixedFormatType.xlTypePDF, @dest == null ? @src + ".pdf" : dest,
                    EXC.XlFixedFormatQuality.xlQualityStandard, true, false);
                Console.WriteLine(SUCCESS);
            }
            catch (Exception ex)
            {
                ThrowException(ex);
            }
            finally
            {
                try
                {
                    if (wb != null)
                        wb.Close(SaveChanges: false);
                }
                catch (Exception ex)
                {
                    ThrowException(ex);
                }
                MSExcel.Quit();
            }
        }
    }
}